<?php
declare (strict_types = 1);

namespace app\middleware;
use app\model\admin\SysOperLog as SysOperLogModel;
use think\facade\Db;

class OperLog
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //只记录POST
        if($request->isGet()){  
            return $next($request);
        }
        
        $request_route_rule = $request->rule()->getRule();

        $perm = str_replace('/', ':', $request_route_rule);
        $menu_name = Db::table('sys_menu')->where('perms',$perm)->value('menu_name');


        $params = $request->param();
        $user_id = $request->create_by ?? 0;
       
        
        if(isset($params['password'])){
            $params['password'] = '******';
        }
        if(isset($params['new_password'])){
            $params['new_password'] = '******';
        }
        if(isset($params['old_password'])){
            $params['old_password'] = '******';
        }
        SysOperLogModel::create([
            'request_method' => $request->method(),
            'oper_url' => $request_route_rule,
            'oper_ip' => $request->ip(),
            'oper_name' => $menu_name,
            'oper_param' => is_array($params) ? json_encode($params) : $params,
        ]);
        

        return $next($request);
    }
}
